package middleware

import (
	"fmt"
	"runtime/debug"

	"gitee.com/botaoshow/yuanxin/web/response"
	"gitee.com/botaoshow/yuanxin/web/y"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

func JsonErrorHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				errorMsg := fmt.Sprintf("%v", err)

				// Log panic error with logrus
				y.WithFields(logrus.Fields{
					"method": c.Request.Method,
					"path":   c.Request.URL.Path,
					"error":  errorMsg,
					"stack":  string(debug.Stack()),
					"ip":     c.ClientIP(),
				}).Error("Panic ERROR")

				response.Resp(c, response.CodeError, errorMsg, nil)
				// Abort request processing
				c.Abort()
			}
		}()

		c.Next()
	}
}
